package pers.xhh.shopapi.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xhh.shopapi.common.Constant;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.common.ResultCode;
import pers.xhh.shopapi.dao.MiPermissionDao;
import pers.xhh.shopapi.entity.MiManagerEntity;
import pers.xhh.shopapi.entity.MiPermissionApiEntity;
import pers.xhh.shopapi.entity.MiPermissionEntity;
import pers.xhh.shopapi.entity.MiRoleEntity;
import pers.xhh.shopapi.entity.vo.permission.MiPermissionListVo;
import pers.xhh.shopapi.entity.vo.permission.MiPermissionTreeVo;
import pers.xhh.shopapi.service.MiManagerService;
import pers.xhh.shopapi.service.MiPermissionApiService;
import pers.xhh.shopapi.service.MiPermissionService;
import pers.xhh.shopapi.service.MiRoleService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
@Service
public class MiPermissionServiceImpl extends ServiceImpl<MiPermissionDao, MiPermissionEntity> implements MiPermissionService {

    @Autowired
    MiManagerService miManagerService;

    @Autowired
    MiRoleService miRoleService;

    @Autowired
    MiPermissionApiService miPermissionApiService;

    @Override
    public Mi listPermission(String type) {
        if (type == null || type.isEmpty()) {
            return Mi.error(ResultCode.ERROR600.getMessage(), ResultCode.ERROR600.getStatus());
        }

        // ->查询
        // list显示
        if (Constant.LIST_PERMISSION.equals(type)) {
            List<MiPermissionListVo> permissionList = getPermissionList();
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), permissionList);
        }

        // 树形显示
        if (Constant.TREE_PERMISSION.equals(type)) {
            List<MiPermissionEntity> list = this.list(new QueryWrapper<>());
            List<MiPermissionTreeVo> permissionTreeVos = getMiPermissionTreeVos(list);
            // 找到一级菜单,递归查询
            List<MiPermissionTreeVo> collect = permissionTreeVos.stream().filter(permissionListVo ->
                    permissionListVo.getLevel() == 0
            ).map((menu) -> {
                menu.setChildren(getChildren(menu, permissionTreeVos));
                return menu;
            }).collect(Collectors.toList());

            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
        }

        return Mi.error(ResultCode.ERROR600.getMessage(), ResultCode.ERROR600.getStatus());
    }

    @Override
    public Mi getMenus(String authorization) {
        // ->能通过拦截器,authorization正确
        // 根据authorization拿到当前用户id
        String userId = JWT.decode(authorization).getAudience().get(0);
        MiManagerEntity byId = miManagerService.getById(userId);
        // 如果当前用户为超级管理员,返回所有,且状态为启用
        Integer roleId = byId.getRoleId();
        Integer mgState = byId.getMgState();
        if (roleId == 0 && mgState == 1) {
            QueryWrapper<MiPermissionEntity> menusQuery = new QueryWrapper<MiPermissionEntity>()
                    .eq("ps_level", 0)
                    .or().eq("ps_level", 1);
            List<MiPermissionEntity> list = this.list(menusQuery);
            List<MiPermissionTreeVo> permissionTreeVos = getMiPermissionTreeVos(list);

            // 找到一级菜单,递归查询
            List<MiPermissionTreeVo> collect = permissionTreeVos.stream().filter(permissionListVo ->
                    permissionListVo.getLevel() == 0
            ).map((menu) -> {
                menu.setChildren(getChildren(menu, permissionTreeVos));
                return menu;
            }).collect(Collectors.toList());

            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
        }

        // ->roleid不为0,且启用状态为1,查询该用户下的角色对应的权限
        if (roleId != 0 && mgState == 1) {
            MiRoleEntity miRoleEntity = miRoleService.getById(roleId);
            if (miRoleEntity == null) {
                return Mi.error(ResultCode.ERROR400.getMessage(), ResultCode.ERROR400.getStatus());
            }
            // 根据psids批量查询
            String psIds = miRoleEntity.getPsIds();
            if (psIds != null) {
                List<String> collect = Arrays.stream(psIds.split(",")).collect(Collectors.toList());
                if (collect.size() > 0) {
                    List<MiPermissionTreeVo> permissionTreeVos1 = getPermissionTreeByIds(collect);
                    return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), permissionTreeVos1);
                }
            }
        }


        return Mi.error(ResultCode.ERROR401.getMessage(), ResultCode.ERROR401.getStatus());

    }

    @Override
    public List<MiPermissionTreeVo> getPermissionTreeByIds(List<String> collect) {
        List<MiPermissionEntity> miPermissionEntities =
                this.baseMapper.selectBatchIds(collect);

        List<MiPermissionTreeVo> permissionTreeVos = getMiPermissionTreeVos(miPermissionEntities);

        // 找到一级菜单,递归查询
        return permissionTreeVos.stream().filter(permissionListVo ->
                permissionListVo.getLevel() == 0
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, permissionTreeVos));
            return menu;
        }).collect(Collectors.toList());
    }

    private List<MiPermissionTreeVo> getMiPermissionTreeVos(List<MiPermissionEntity> list) {
        return list.stream().map(item -> {
            MiPermissionTreeVo miPermissionTreeVo = new MiPermissionTreeVo();
            miPermissionTreeVo.setId(item.getPsId());
            miPermissionTreeVo.setAuthName(item.getPsName());
            miPermissionTreeVo.setLevel(item.getPsLevel());
            miPermissionTreeVo.setPid(item.getPsPid());
            // 从permissionApi查询
            QueryWrapper<MiPermissionApiEntity> psId =
                    new QueryWrapper<MiPermissionApiEntity>().eq("ps_id", item.getPsId());
            MiPermissionApiEntity one = miPermissionApiService.getOne(psId);
            String path = "";
            if (one != null) {
                path = one.getPsApiPath();
            }
            miPermissionTreeVo.setPath(path);
            return miPermissionTreeVo;
        }).collect(Collectors.toList());
    }

    private List<MiPermissionListVo> getPermissionList() {
        List<MiPermissionEntity> list = this.list(new QueryWrapper<>());
        return list.stream().map(item -> {
            MiPermissionListVo miPermissionListVo = new MiPermissionListVo();
            miPermissionListVo.setId(item.getPsId());
            miPermissionListVo.setAuthName(item.getPsName());
            miPermissionListVo.setLevel(item.getPsLevel());
            miPermissionListVo.setPid(item.getPsPid());
            // 从permissionApi查询
            QueryWrapper<MiPermissionApiEntity> psId =
                    new QueryWrapper<MiPermissionApiEntity>().eq("ps_id", item.getPsId());
            MiPermissionApiEntity one = miPermissionApiService.getOne(psId);
            String path = "";
            if (one != null) {
                path = one.getPsApiPath();
            }
            miPermissionListVo.setPath(path);
            return miPermissionListVo;
        }).collect(Collectors.toList());
    }

    // 找到一级菜单下的子菜单,递归查找菜单的所有子菜单
    private List<MiPermissionTreeVo> getChildren(MiPermissionTreeVo root, List<MiPermissionTreeVo> all) {
        List<MiPermissionTreeVo> collect = all.stream().filter(miPermissionTreeVo ->
                miPermissionTreeVo.getPid().equals(root.getId())
        )
                .map((menu) -> {
                    // 找到子菜单
                    if(menu.getLevel() <= 1){
                        menu.setChildren(getChildren(menu, all));
                    }
                    return menu;
                }).collect(Collectors.toList());

        return collect;
    }
}
